package com.zhang.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhang.pojo.UserBean;
import com.zhang.service.IUserService;
import com.zhang.util.ResultVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@Api(tags = "用户控制接口")
@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private IUserService userService;

    @ApiOperation("登录")
    @GetMapping("login")
    ResultVo login(String username, String pwd, HttpServletRequest req){
        UserBean user = userService.login(username, pwd);
        ResultVo resultVo = new ResultVo();
        if(user != null){
            req.getSession().setAttribute("user",user);
            resultVo.setUserBean(user);
            resultVo.setCode("ok");
            return resultVo;
        }
        resultVo.setCode("no");
        return resultVo;
    }

    @ApiOperation("根据用户id查询用户")
    @GetMapping("findById")
    public UserBean findById(int id){
       return userService.findById(id);
    }

    @ApiOperation("根据用户名动态查询并分页")
    @GetMapping("findPageAndItem")
    IPage<UserBean> findPageAndItem(Integer current,
                                    Integer pageSize,
                                    String username){
       return userService.findByPage(new Page<>(current,pageSize),username);
    }

    @ApiOperation("添加用户")
    @PostMapping("add")
    public String add( String username,
                       String realName,
                      Integer[] roleIds){

        try {
            UserBean userBean = new UserBean();
            userBean.setUsername(username);
            userBean.setReal(realName);
            userService.add(userBean,roleIds);
            return "ok";
        } catch (Exception e) {
            return "no";
        }
    }

    @ApiOperation("删除用户")
    @DeleteMapping("del/{id}")
    public String del(@PathVariable("id") int id){
        try {
            userService.del(id);
            return "ok";
        } catch (Exception e) {
            return "no";
        }
    }

    @ApiOperation("修改用户角色")
    @PutMapping("update")
    public String update(int userId,int[] roleIds){
        try {
            userService.update(userId, roleIds);
            return "ok";
        } catch (Exception e) {
            return "no";
        }
    }

    @ApiOperation("修改密码")
    @PutMapping("updatePwd")
    public String update(HttpServletRequest req,String pwd){
        try {
            UserBean user = (UserBean) req.getSession().getAttribute("user");
            userService.updatePwd(user.getId(),pwd);
            return "ok";
        } catch (Exception e) {
            return "no";
        }
    }


}
